package com.sh.d1.gameserver;

import com.alibaba.fastjson.JSONObject;
import com.sh.d1.gameserver.model.UserManager;
import com.sh.d1.gameserver.msg.GameMsgProtocol;
import com.sh.util.LoadStatistic;
import com.sh.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.Executors;

/**
 * 订阅者
 */
public class RedisSusbcriber {

    static private final Logger LOGGER = LoggerFactory.getLogger(RedisSusbcriber.class);


    /**
     * REDIS通信通道
     */
    static public final String CHANNEL_USER_OFFLINE = "UserOffline";

    public RedisSusbcriber() {
    }

    /**
     * 开始订阅
     */
    static public void startSubcriber() {
        Executors.newSingleThreadExecutor().submit(RedisSusbcriber::subscribe);
    }

    /**
     * 订阅
     */
    static public void subscribe() {
        RedisUtil.getRedis().subscribe(new JedisPubSub() {
            @Override
            public void onMessage(String ch, String msg) {
                if (!CHANNEL_USER_OFFLINE.equals(ch) || null == msg) {
                    return;
                }
                LOGGER.info("收到网关的用户离线通知,userId:{}", msg);
                JSONObject jsonObj = JSONObject.parseObject(msg);
                if (null == jsonObj) {
                    LOGGER.info("JSON 对象为空");
                    return;
                }
                int gatewayServerId = jsonObj.getIntValue("gatewayServerId");
                int remoteSessionId = jsonObj.getIntValue("remoteSessionId");
                int userId = jsonObj.getIntValue("userId");
                if (gatewayServerId <= 0 ||  remoteSessionId <= 0) {
                    LOGGER.info("网关服务器id 或远程会话id 为空");
                    return;
                }
                //移除广播信息
                Broadcaster.removeUserClientId(gatewayServerId, remoteSessionId);
                //通知在线用户
                GameMsgProtocol.UserQuitResult.Builder resultBuilder = GameMsgProtocol.UserQuitResult.newBuilder();
                resultBuilder.setQuitUserId(userId);

                // 构建结果并发送
                GameMsgProtocol.UserQuitResult newResult = resultBuilder.build();
                Broadcaster.broadcast(newResult);

                UserManager.removeByUserId(userId);

                //移除负载统计数据
                LoadStatistic.removeUserId(userId);

            }
        }, CHANNEL_USER_OFFLINE);
    }
}
